package com.xinpu.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinpu.entity.TCompany;
import com.xinpu.entity.TCompanyUser;
import com.xinpu.enums.PublicEnum;
import com.xinpu.service.*;
import com.xinpu.util.PasswordUtils;
import com.xinpu.vo.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * LoginController
 *
 * @author ayuan
 * @date 2020/12/14
 */
@RestController
@RequestMapping("login")
public class LoginController {
    @Autowired
    private ITCompanyService itCompanyService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ITCompanyUserService itCompanyUserService;
    /**
     * 获取密码加密后的数据
     *
     * @param map
     * @return
     */
    @PostMapping("/getPasswordAndSalt")
    public ResponseMessage getPasswordAndSalt(@RequestBody Map<String, String> map) {
        String salt = RandomUtil.randomString(6);
        String password = PasswordUtils.generatePwd(salt, map.get("password"));
        Map<String, String> hasMap = new HashMap<>();
        hasMap.put("salt", salt);
        hasMap.put("password", password);
        return ResponseMessage.ok(hasMap);
    }


    /**
     * 用户登录
     *
     * @param map
     * @return
     */
    @PostMapping("/userLogin")
    public ResponseMessage userLogin(@RequestBody Map<String, String> map) {
        TCompanyUser tCompanyUser = itCompanyUserService.getOne(Wrappers.<TCompanyUser>lambdaQuery().eq(TCompanyUser::getPhone, map.get("username")));
        if (tCompanyUser == null) {
            return ResponseMessage.error("账号或密码错误");
        }
        boolean password = PasswordUtils.validatePwd(map.get("password"), tCompanyUser.getSalt(), tCompanyUser.getPassword());
        if (!password) {
            return ResponseMessage.error("账号或密码错误");
        }
        TCompany tCompany = itCompanyService.getOne(Wrappers.<TCompany>lambdaQuery().eq(TCompany::getTenantId, tCompanyUser.getTenantId()));
        if (tCompany.getStatus().equals(PublicEnum.NO.getValue())) {
            return ResponseMessage.error("该账号已过期");
        }
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(tCompany.getStartTime())) {
            return ResponseMessage.error("该账号暂未开启");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("id", tCompanyUser.getId().toString());
        TokenService.TokenResult generate = tokenService.generate(tokenMap);
        return ResponseMessage.ok(generate.getToken());
    }

}
